package com.liveneo.adapter.outinterface.web.platform;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.liveneo.adapter.base.entity.PrpmCaseInfo;
import com.liveneo.adapter.base.support.LogUtils;
import com.liveneo.adapter.mobile.model.SurveyLossConfirm;
import com.liveneo.adapter.mobile.model.SurveyUploadImageData;
import com.liveneo.adapter.outinterface.thread.UploadImgLossItemThread;
import com.liveneo.adapter.outinterface.thread.UploadLossItemIdCypImageThread;
import com.liveneo.adapter.outinterface.thread.UploadVideoLossItemIdThread;
import com.liveneo.adapter.outinterface.thread.VideoCaseEndThread;
import com.liveneo.adapter.outinterface.util.DBTableUtil;
import com.liveneo.adapter.outinterface.util.JsonUtils;
import com.liveneo.adapter.outinterface.util.ResultInfo;
import com.liveneo.adapter.outinterface.util.ThreadPool;
import com.liveneo.adapter.outinterface.web.platform.request.ApplySurveyReassign;
import com.liveneo.adapter.outinterface.web.platform.request.TaskNormalEndRequest;
import com.liveneo.adapter.outinterface.web.platform.request.dto.SurveyDelegateRequestDto;
import com.liveneo.adapter.outinterface.web.platform.response.BaseResponse;

/**
  * @Description: 对WEB提供接口
  * @author liveneo-shuqw
  * @date 2016年10月17日 下午9:09:40
  * @Copyright: Copyright (c) 2016 
  * @Company: 北京朗泰
  * @version 3.0
  */
@Controller
@RequestMapping("/survey")
public class WebPlatformController {

	@Autowired
	private DBTableUtil dbTableUtil;
	
	
	@RequestMapping("/dispatchSurveyDelegate")
	@ResponseBody
	public String dispatchSurveyDelegate(@RequestBody SurveyDelegateRequestDto request){
		LogUtils.info("查勘定损任务调度---->接收请求参数："+JsonUtils.toJson(request));
		BaseResponse baseResponse = new BaseResponse();
		try {
			List<SurveyDelegateRequestDto> sdList = new ArrayList<SurveyDelegateRequestDto>();
			sdList.add(request);
			ResultInfo resultInfo = ClaimInterface.applySurveyDelegate(sdList);
			if("000".equals(resultInfo.getResultCode())){
				baseResponse.setExtMessage("成功");
				baseResponse.setResultCode("0");
			}else{
				baseResponse.setExtMessage("查勘平台：调度失败"+resultInfo.getResultMsg());
				baseResponse.setResultCode("1");
			}
		} catch (Exception e) {
			LogUtils.error("接口任务调度dispatchSurveyDelegate---->服务器异常：\n",e);
			baseResponse.setExtMessage("查勘平台：调度失败未知或网络异常");
			baseResponse.setResultCode("1");
		}
		return JsonUtils.toJson(baseResponse);
	}
	
	
	/**
     * @Title: 
     * @Description: 影像资料上传
     * @param @return 设定文件
     * @return String 返回类型
     * @throws
    */
   @RequestMapping("/uploadImageData")
   @ResponseBody
	public String uploadImageData(@RequestBody SurveyUploadImageData data) {
		LogUtils.info("影像资料上传----->接收请求参数：\n" + JsonUtils.toJson(data));
		BaseResponse baseResponse = new BaseResponse();
		try {
			String caseNo = data.getCaseNo();
			List<String> lossItemIdList = data.getLossItemIdList();
			if(lossItemIdList == null || lossItemIdList.size() == 0){
				baseResponse.setExtMessage("失败：上传列表任务编号不能为空");
				baseResponse.setResultCode("1");
				return JsonUtils.toJson(baseResponse);
			}
			// 车易陪上传图片
			if("1".equals(data.getTaskType())){
				for (String lossItemCypId : lossItemIdList) {
					int lossItemCypCount = dbTableUtil.selectLossItemCypCountById(lossItemCypId);
					int exCount = (lossItemCypCount + 10 - 1) / 10;
					//开启线程
					ThreadPool uploadTheadPool = ThreadPool.getThreadPool(exCount);
					List<Runnable> runnables = new ArrayList<Runnable>();
					for (int i = 0; i < exCount; i++) {
						runnables.add(new UploadLossItemIdCypImageThread(caseNo, lossItemCypId ,i+1));
					}
					uploadTheadPool.execute(runnables);
					uploadTheadPool.destroy();
					baseResponse.setExtMessage("成功");
					baseResponse.setResultCode("0");
				}
			}else{
				// 精友上传图片
				for (String lossItemId : lossItemIdList) {
					// 获取上传图片总数
					int uploadImgCount = dbTableUtil.selectUploadImgCountByCaseNoLossItemId(caseNo, lossItemId);
					int exCount = (uploadImgCount + 10 - 1) / 10;
					//视频总数
					int uploadVideoCount = dbTableUtil.selectUploadVideoCountByCaseNoLossItemId(caseNo, lossItemId);
					int vdCount = (uploadVideoCount + 10 - 1) / 10;
					//开启线程
					ThreadPool uploadTheadPool = ThreadPool.getThreadPool(exCount+vdCount);
					List<Runnable> runnables = new ArrayList<Runnable>();
					for (int i = 0; i < exCount; i++) {
						runnables.add(new UploadImgLossItemThread(caseNo, lossItemId ,i+1));
					}
					for (int i = 0; i < vdCount; i++) {
						runnables.add(new UploadVideoLossItemIdThread(caseNo, lossItemId, i+1));
					}
					uploadTheadPool.execute(runnables);
					uploadTheadPool.destroy();
					baseResponse.setExtMessage("成功");
					baseResponse.setResultCode("0");
				}
			}
		
		} catch (Exception e) {
			LogUtils.error("接口图片上传uploadImageData---->服务器异常：\n",e);
			baseResponse.setExtMessage("查勘平台：上传失败未知或网络异常");
			baseResponse.setResultCode("1");
		}
		return JsonUtils.toJson(baseResponse);
	}

   /**
     * @Title: 用户定损结果确认
     * @Description: 
     * @param @return 设定文件
     * @return String 返回类型
     * @throws
    */
   @RequestMapping("/singleLossConfirm")
   @ResponseBody
	public String singleLossConfirm(@RequestBody SurveyLossConfirm data) {
		LogUtils.info("用户定损结果确认----->接收请求参数：\n" + JsonUtils.toJson(data));
		BaseResponse baseResponse = new BaseResponse();
		try {
			//调用定损接口
//			ResultInfo resultInfo = ClaimInterface.confirmEvaluate(data.getCaseNo(), data.getIsAgree(),
//					data.getConfirmType(), data.getConfirmBy(), new Date());
//			if ("0000".equals(resultInfo.getResultCode())) {
//				baseResponse.setExtMessage("查勘平台：户定损结果确认成功");
//				baseResponse.setResultCode("0");
//			} else {
				baseResponse.setExtMessage("查勘平台：户定损结果确认失败，原因：接口废弃");
				baseResponse.setResultCode("1");
//			}
		} catch (Exception e) {
			LogUtils.error("接口用户定损结果确认singleLossConfirm---->服务器异常：\n",e);
			baseResponse.setExtMessage("查勘平台：户定损结果确认未知或网络异常");
			baseResponse.setResultCode("1");
		}
		return JsonUtils.toJson(baseResponse);
	}

   /**
     * @Title: 任务正常结束
     * @Description: 
     * @param @return 设定文件
     * @return String 返回类型
     * @throws
    */
	@RequestMapping("/taskNormalEnd")
	@ResponseBody
	public String taskNormalEnd(@RequestBody TaskNormalEndRequest request) {
		BaseResponse baseResponse = new BaseResponse();
		try {
			PrpmCaseInfo caseInfo = dbTableUtil.selectCaseInfoByNo(request.getCaseNo(), null);
			if(caseInfo == null){
				 throw new RuntimeException("案件号错误,案件号："+request.getCaseNo());
			}
			//调用核心计费接口
			ResultInfo resultInfo = ClaimInterface.videoCaseEndService(request.getCaseNo(),caseInfo.getBillingType());
			ThreadPool uploadTheadPool = ThreadPool.getThreadPool(1);
			List<Runnable> runnables = new ArrayList<Runnable>();
			if ("999".equals(resultInfo.getResultCode())) {
				runnables.add(new VideoCaseEndThread(request.getCaseNo(),caseInfo.getBillingType()));
			}
			uploadTheadPool.execute(runnables);
			uploadTheadPool.destroy();
			baseResponse.setExtMessage("成功");
			baseResponse.setResultCode("0");
		} catch (Exception e) {
			LogUtils.error("接口任务正常结束taskNormalEnd---->服务器异常：\n",e);
			baseResponse.setExtMessage("任务正常结束调用未知或网络异常");
			baseResponse.setResultCode("1");
		}
		return JsonUtils.toJson(baseResponse);
	}
	
   /***
    * @Title: 查勘定损任务改派
    * @Description: 
    * @param @return 设定文件
    * @return String 返回类型
    * @throws
   */
	@RequestMapping("/applySurveyReassign")
	@ResponseBody
	public String applySurveyReassign(@RequestBody List<ApplySurveyReassign> reassign) {
		LogUtils.info("查勘定损任务改派----->请求接收参数：\n" + JsonUtils.toJson(reassign));
		BaseResponse baseResponse = new BaseResponse();
		//Map<String, String> param = new HashMap<String, String>();
		try {
//			List<SurveyReassignType> srtList = new ArrayList<SurveyReassignType>();
//			int i = 1;
//			for (ApplySurveyReassign asr : reassign) {
//				SurveyReassignType surveyReassignType = new SurveyReassignType();
//				PrpmLossItem lossItem = dbTableUtil.selectLossItemByCaseNoAndLossId(asr.getCaseNo(), asr.getLossId());
//				// 判断任务信息
//				if (lossItem == null) {
//					param.put("888" + i, "案件号：" + asr.getCaseNo() + "，任务号：" + asr.getLossId() + "申请改派失败，原因：任务信息不存在或错误");
//					continue;
//				}
//				//surveyReassignType.setLossId(lossItem.getLossid());
//				surveyReassignType.setLossName(lossItem.getLossName());
//				surveyReassignType.setSurveyReassignType(asr.getSurveyReassignType());
//				//surveyReassignType.setLossType(lossItem.getLosstype());
//				// 添加List
//				srtList.add(surveyReassignType);
//				// 请求核心
//				ResultInfo resultInfo = ClaimInterface.applySurveyReassign(asr.getCaseNo(),"0",srtList,asr.getReassignReason());
//				srtList.clear();
//				if ("999".equals(resultInfo.getResultCode())) {
//					param.put("999" + i, "案件号：" + asr.getCaseNo() +"，任务号："+asr.getLossId()+"申请改派失败，原因："+ resultInfo.getResultMsg());
//				}
//				i++;
//			}
//			if (param.isEmpty()) {
//				baseResponse.setExtMessage("查勘平台：查勘定损任务申请改派成功");
//				baseResponse.setResultCode("0");
//			} else {
//				StringBuffer sb = new StringBuffer();
//				for (String str : param.keySet()) {
//					sb.append(param.get(str));
//				}
//				baseResponse.setExtMessage("查勘平台：查勘定损任务申请改派" + sb.toString());
//				baseResponse.setResultCode("2"); // 部分成功
//			}
			baseResponse.setExtMessage("查勘平台：查勘定损任务申请改失败，原因：接口废弃");
			baseResponse.setResultCode("1"); // 部分成功
		} catch (Exception e) {
			LogUtils.error("接口查勘定损任务改派applySurveyReassign---->服务器异常：\n", e);
			baseResponse.setExtMessage("查勘平台：查勘定损任务申请改派未知或网络异常");
			baseResponse.setResultCode("1");
		}
		return JsonUtils.toJson(baseResponse);
	}
	
	@RequestMapping("/updateCaseInfoBillState")
	@ResponseBody
	public String updateCaseInofStateAndBill(@RequestBody TaskNormalEndRequest request){
		BaseResponse baseResponse = new BaseResponse();
		try{
			if(StringUtils.isBlank(request.getCaseNo())){
				throw new RuntimeException("案件号不能为空");
			}
			dbTableUtil.updateCaseInofStateAndBill(request.getCaseNo());
			baseResponse.setExtMessage("查勘平台：查勘任务计费状态变更成功");
			baseResponse.setResultCode("0"); // 成功
		} catch (Exception e) {
			LogUtils.error("接口查勘任务计费状态变更 updateCaseInofState---->服务器异常：\n", e);
			baseResponse.setExtMessage("查勘平台：查勘任务计费状态变更未知或案件号异常");
			baseResponse.setResultCode("1");
		}
		return JsonUtils.toJson(baseResponse);
	}
	
  
}
